package com.ruoyi.whole.controller;

import java.io.*;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.whole.domain.*;
import com.ruoyi.whole.service.IInfoWholeEvaluateService;
import com.ruoyi.whole.service.IInfoWholeIndexService;
import com.ruoyi.whole.service.IInfoWholePlanService;
import freemarker.template.Configuration;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.SecurityUtils;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.whole.service.IInfoWholeTargetService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 目标管理-部门整体信息Controller
 *
 * @author ruoyi
 * @date 2022-02-10
 */
@RestController
@RequestMapping("/whole/target")
@Api(tags = "目标管理-部门整体信息")
public class InfoWholeTargetController extends BaseController {
    @Autowired
    private IInfoWholeTargetService infoWholeTargetService;
    @Resource
    private IInfoWholeEvaluateService infoWholeEvaluateService;
    @Resource
    private IInfoWholePlanService iInfoWholePlanService;
    @Resource
    private ISysDeptService deptService;
    @Resource
    private IInfoWholeIndexService iInfoWholeIndexService;

    /**
     * 查询目标管理-部门整体信息列表
     */
    @PreAuthorize("@ss.hasPermi('whole:target:list')")
    @GetMapping("/list")
    @ApiOperation("查询目标管理")
    @ApiImplicitParam(name = "infoWholeTarget", value = "实体类", dataType = "InfoWholeTarget")
    public TableDataInfo list(InfoWholeTarget infoWholeTarget) {
        startPage();
        List<InfoWholeTarget> list = infoWholeTargetService.selectInfoWholeTargetList(infoWholeTarget);
        return getDataTable(list);
    }

    /**
     * 导出目标管理-部门整体信息列表
     */
    @PreAuthorize("@ss.hasPermi('whole:target:export')")
    @Log(title = "目标管理-部门整体信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoWholeTarget infoWholeTarget) {
        List<InfoWholeTarget> list = infoWholeTargetService.selectInfoWholeTargetList(infoWholeTarget);
        ExcelUtil<InfoWholeTarget> util = new ExcelUtil<InfoWholeTarget>(InfoWholeTarget.class);
        util.exportExcel(response, list, "目标管理-部门整体信息数据");
    }

    /**
     * 获取目标管理-部门整体信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('whole:target:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取目标管理")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(infoWholeTargetService.selectInfoWholeTargetById(id));
    }

    /**
     * 新增目标管理-部门整体信息
     */
    @PreAuthorize("@ss.hasPermi('whole:target:add')")
    @Log(title = "目标管理-部门整体信息", businessType = BusinessType.INSERT)
    @ApiOperation("新增目标管理-部门整体信息")
    @ApiImplicitParam(name = "infoWholeTarget", value = "实体类", dataType = "InfoWholeTarget")
    @PostMapping
    public AjaxResult add(@RequestBody InfoWholeTarget infoWholeTarget) {
        int i = infoWholeTargetService.insertInfoWholeTarget(infoWholeTarget);
        AjaxResult result = toAjax(i);
        result.put("id", infoWholeTarget.getId());
        return result;
    }

    /**
     * 修改目标管理-部门整体信息
     */
    @PreAuthorize("@ss.hasPermi('whole:target:edit')")
    @Log(title = "目标管理-部门整体信息", businessType = BusinessType.UPDATE)
    @ApiOperation("修改目标管理")
    @ApiImplicitParam(name = "infoWholeTarget", value = "实体类", dataType = "InfoWholeTarget")
    @PutMapping
    public AjaxResult edit(@RequestBody InfoWholeTarget infoWholeTarget) {
        return toAjax(infoWholeTargetService.updateInfoWholeTarget(infoWholeTarget));
    }

    /**
     * 删除目标管理-部门整体信息
     */
    @PreAuthorize("@ss.hasPermi('whole:target:remove')")
    @Log(title = "目标管理-部门整体信息", businessType = BusinessType.DELETE)
    @ApiOperation("删除目标管理")
    @ApiImplicitParam(name = "ids", value = "id", dataType = "Long")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(infoWholeTargetService.deleteInfoWholeTargetByIds(ids));
    }

    /**
     * 部门项目支出绩效自评情况汇总表
     */
    @GetMapping("/summarizing")
    @ApiOperation("目标管理-测试")
    @ApiImplicitParam(name = "industryTitle", value = "部门名称", dataType = "String")
    public AjaxResult list(String industryTitle) {
        return AjaxResult.success(infoWholeTargetService.selectInfoWholeSummarizingVoList(industryTitle));
    }

    /**
     * 审核/上报 部门项目
     * 上报 修改审核状态 0 未上报 1 待审核 2 驳回 3 通过
     * 审核 主要修改审核意见 和 审核状态 0 未上报 1 待审核 2 驳回 3 通过
     *
     * @param infoWholeTarget
     * @return
     */
    @PreAuthorize("@ss.hasPermi('whole:target:report')")
    @RequestMapping(value = "/auditStatus", method = RequestMethod.POST)
    @ApiOperation("部门项目审核上报")
    @ApiImplicitParam(name = "infoWholeTarget", value = "实体类", dataType = "InfoWholeTarget")
    public AjaxResult auditStatus(@RequestBody InfoWholeTarget infoWholeTarget) {
        return toAjax(infoWholeTargetService.updateInfoWholeTarget(infoWholeTarget));
    }
    /**
     * 部门项目审核列表查询
     */
    @RequestMapping(value = "/auditStatusList", method = RequestMethod.GET)
    @ApiOperation("部门项目审核列表查询")
    @ApiImplicitParam(name = "infoWholeTarget", value = "实体类", dataType = "InfoWholeTarget")
    public TableDataInfo auditStatusList(InfoWholeTarget infoWholeTarget) {
        startPage();
        //只查询当前登录用户审核的项目 也就是所属处室 dept_id 并且 audit_status 状态不等于0的
        infoWholeTarget.setDeptId(SecurityUtils.getDeptId());
        List<InfoWholeTarget> list = infoWholeTargetService.auditInfoWholeTargetList(infoWholeTarget);
        return getDataTable(list);
    }

    /**
     * 批量新增
     */
    @RequestMapping(value = "/addBulk", method = RequestMethod.POST)
    @ApiOperation("批量新增")
    @ApiImplicitParam(name = "infoBulkAddVos", value = "实体类", dataType = "InfoBulkAddVo")
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    public AjaxResult addBulk(@RequestBody InfoBulkAddVo infoBulkAddVos) {
        int i = infoWholeTargetService.batchInsert(infoBulkAddVos);
        AjaxResult result = toAjax(i);
        InfoWholeTarget infoWholeTarget = new InfoWholeTarget();
        result.put("id", infoWholeTarget.getId());
        return result;
    }
    /**
     * 查询部门整体审核信息列表
     */
    @GetMapping("/shlist")
    public TableDataInfo shlist(InfoWholeTarget infoWholeTarget) {
        startPage();
        List<InfoWholeTarget> list = infoWholeTargetService.selectInfoWholeTargetLists(infoWholeTarget);
        return getDataTable(list);
    }

    /**
     * 目标部门整体评价报告第三方导出
     */
    @PostMapping("/downloadThird/{id}")
    @ResponseBody
    @ApiOperation("部门整体评价报告下载")
    @ApiImplicitParam(name = "id", value = "编号", dataType = "Long")
    public AjaxResult downloadThird(@PathVariable("id")Long id) {
        String fileName = null;
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            String dirPath = InfoWholeTargetController.class.getResource("/report/template").getPath();
            configuration.setDirectoryForTemplateLoading(new File(dirPath));
            Template template = configuration.getTemplate("wz_dept.ftl", "utf-8");
            /**
             * 把查到的东西放进map中
             */
            Map<String, Object> data = new HashMap<>();
            InfoWholeTarget infoWholeTarget = infoWholeTargetService.selectInfoWholeTargetsById(id);

            String title ="省级单位(部门)整体支出绩效目标表";
            fileName = title;

            /**
             * map里放的东西
             */
            data.put("fileName", title);
            //现在map里的东西是title，部门整体信息target和自评表的东西
            data.put("infoWholeTarget", infoWholeTarget);

            /**
             * 根据部门自评表里的部门编号查询部门指标信息里的对应信息
             */
            List<InfoWholeIndex> infoWholeIndices = iInfoWholeIndexService.selectInfoWholeIndicesId(infoWholeTarget.getId());
            for(InfoWholeIndex infoWholeIndex:infoWholeIndices){
                infoWholeIndex.setMergeNumber((infoWholeIndices.stream().filter(item -> item.getTargetOne().equals(infoWholeIndex.getTargetOne())).count()-1)+"");
                infoWholeIndex.setMergeTwoNumber((infoWholeIndices.stream().filter(item -> item.getTargetTwo().equals(infoWholeIndex.getTargetTwo())).count()-1)+"");
            }
            data.put("infoWholeIndices", infoWholeIndices);
            data.put("year", DateUtils.parseDateToStr("yyyy",new Date()));

            System.out.println("++++"+JSONObject.toJSONString(data));
            Writer out = null;

            String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
            File outFile = new File(downloadPath + ".xlsx");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(data, out);
            out.close();
            System.out.println("................word文档生成成功 !.............");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }


        return AjaxResult.success(fileName + ".xlsx");
    }
}
